package com.lvyq.myplayer.ui.fragment.singer

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.OnScrollListener
import com.lvyq.myplayer.R
import com.lvyq.myplayer.adapter.singer.SingerSongAdapter
import com.lvyq.myplayer.model.singer.SingerSongBean
import com.lvyq.myplayer.parcelable.SongInfoData
import com.lvyq.myplayer.ui.activity.AudioPlayerActivity
import com.lvyq.myplayer.util.ThreadUtil
import com.lvyq.myplayer.util.NetworkUtils
import com.lvyq.myplayer.util.URLProviderUtils

/**
 * 文件描述：SingerSongPagerFragment
 * 作者：lvyq
 * 创建时间：2025-04-25
 * 修改时间：2025-04-25
 */
class SingerSongPagerFragment(var singerId:Int): Fragment() {


    lateinit var singerSongView:RecyclerView


    val singerSongAdapter by lazy { getAdapter() }


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return initView()
    }

    private fun initView(): View? {
        var view  = View.inflate(context, R.layout.fragment_singer_song,null)
        singerSongView=view.findViewById(R.id.singerSongView)
        // 设置LinearLayoutManager（默认纵向） // 或者 GridLayoutManager(context, 2) 等
        singerSongView.layoutManager = LinearLayoutManager(context)
        //适配
        singerSongView.adapter=singerSongAdapter

        initData()
        initListener()
        return view

    }

    private fun initListener() {
        singerSongView.addOnScrollListener(object :OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                //空闲状态
                if (newState== RecyclerView.SCROLL_STATE_IDLE){
                    //判断滑动到最后一条
                    var layoutManager = recyclerView.layoutManager
                    if (layoutManager is LinearLayoutManager){
                        //只有线性布局才有最后一条的概念
                        val manager=layoutManager
                        //获取最后条目
                        var findLastVisibleItemPosition = manager.findLastVisibleItemPosition()

                        //无最新数据
                        if (findLastVisibleItemPosition==singerSongAdapter.totalCount){
                            return
                        }
                        if (findLastVisibleItemPosition==singerSongAdapter.itemCount-1){
                            loadMore()
                        }

                    }
                }

            }
        })
    }


    private fun loadMore() {
            val pageNum = (singerSongAdapter.itemCount - 1) / 15 + 1
            val url = URLProviderUtils.getSingerSongPage(singerId,pageNum,15)
            NetworkUtils.get(
                url = url,
                responseClass = SingerSongBean::class.java,
                successCallback = { pageData ->
                    singerSongAdapter.loadMore(
                        ArrayList(pageData.rows),
                        pageData.total
                    )
                },
                errorCallback = { errorMsg ->
                    Toast.makeText(context, "加载失败：$errorMsg", Toast.LENGTH_SHORT).show()
                    Log.e("SingerSongPagerFragment", "加载失败：$errorMsg")
                }
            )
    }




    private fun initData() {
        val url = URLProviderUtils.getSingerSongPage(singerId,1,15)
        NetworkUtils.get(
            url = url,
            responseClass = SingerSongBean::class.java,
            successCallback = { pageData ->
                singerSongAdapter.initData(
                    ArrayList(pageData.rows),
                    pageData.total
                )
            },
            errorCallback = { errorMsg ->
                Toast.makeText(context, "加载失败：$errorMsg", Toast.LENGTH_SHORT).show()
                Log.e("SingerSongPagerFragment", "加载失败：$errorMsg")
            }
        )
    }

    fun getAdapter():SingerSongAdapter{
        return SingerSongAdapter(context,object :
            SingerSongAdapter.OnItemClickListener{
            override fun onItemClick(position: Int, song: SongInfoData) {
                // 点击跳转播放页面,查询该音乐下的所属专辑下的所有歌
                println("点击了"+song.title)
               startAudioPlayActivity(song)
            }
        })
    }


    /**
     * 跳转到歌曲播放界面
     */
    fun  startAudioPlayActivity(data: SongInfoData){

        if (data.albumId==null){
            ThreadUtil.runOnMainThread({
                // 点击跳转播放页面
                var intent = Intent(context, AudioPlayerActivity::class.java)
                intent.putExtra("position",0)
                intent.putExtra("data",data)
                var lastSong= ArrayList<SongInfoData>()
                data.position=0
                data.isPlaying=1
                lastSong.add(data)
                intent.putParcelableArrayListExtra("songLst",lastSong)
                //跳转播放页
                context?.let {
                    it.startActivity(intent)
                }
            })
        }else{
            //不分页
            val url = URLProviderUtils.getSingerSongPage100BySongId(
                data.albumId,data.singerId)
            NetworkUtils.get(
                url = url,
                responseClass = SingerSongBean::class.java,
                successCallback = { pageData ->
                    // 先遍历列表重置position的播放状态
                    pageData.rows.forEachIndexed { index, song ->
                        if(song.id==data.id){
                            song.isPlaying=1
                            song.position=index
                            data.position=song.position
                        }
                    }
                    ThreadUtil.runOnMainThread({
                        // 点击跳转播放页面
                        var intent = Intent(context, AudioPlayerActivity::class.java)
                        intent.putExtra("position",data.position)
                        intent.putExtra("data",data)
                        intent.putParcelableArrayListExtra("songLst",pageData.rows)
                        //跳转播放页
                        context?.let {
                            it.startActivity(intent)
                        }
                    })
                },
                errorCallback = { errorMsg ->
                    Toast.makeText(context, "加载失败：$errorMsg", Toast.LENGTH_SHORT).show()
                    Log.e("SingerSongPagerFragment", "加载失败：$errorMsg")
                }
            )

        }
        }


}